package com.origin.app.page.location_records

import android.view.animation.LinearInterpolator
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.amap.api.maps.AMap
import com.amap.api.maps.AMapUtils
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.origin.app.bean.BaseNetBean
import com.origin.app.bean.CompanyPointBean
import com.origin.app.utils.AppUtils
import com.origin.app.utils.NetAppUtils
import com.origin.app.utils.TimeUtils
import com.origin.app.utils.dialog.DialogUtils
import com.origin.baselibrary.viewmodel.BaseViewModel
import com.origin.utils.log.LogUtils
import ikidou.reflect.TypeBuilder
import java.util.Timer
import java.util.TimerTask
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.atan2


class ActivityLocationRecordsViewModel:BaseViewModel() {
     val refreshLocationRecordsMutableLiveData = MutableLiveData<Long>()
     val refreshCompanyPointBeanInfoMutableLiveData = MutableLiveData<CompanyPointBean>()
    private  val locationRecords= mutableListOf<CompanyPointBean>()
     val locationRecordsLatLng= mutableListOf<LatLng>()
    fun getLocationRecordsByTaskId(companyPointBean: CompanyPointBean,startTime:Long, endTime:Long) {
        DialogUtils.showLoadDialog("加载中...")
        val jsonString: String =
            "{\"taskId\":${companyPointBean.taskId},\"startDate\":\"${TimeUtils.formatterTimeByLongString(startTime)}\",\"endDate\":\"${TimeUtils.formatterTimeByLongString(endTime)}\"}"

        LogUtils.__e("请求内容   ${jsonString}")

        val type1 = TypeBuilder.newInstance(BaseNetBean::class.java)
            .beginSubType(List::class.java)
            .addTypeParam(CompanyPointBean::class.java)
            .endSubType()
            .build()

        viewModelSuspend {
            val bean = NetAppUtils.privatePostJsonStr<BaseNetBean<List<CompanyPointBean>>>(
                NetAppUtils.getLocationRecordsByTaskIdUrl,
                jsonString,
                type1,
                viewModelScope
            );
            if (bean.isOk) {
                var list = bean.data.size;
               LogUtils.__e("路径长度  ${list}")
                locationRecords.clear()
                locationRecords.addAll(bean.data)
                locationRecordsLatLng.clear()
                locationRecords.forEach {
                    locationRecordsLatLng.add(LatLng(it.lat.toDouble(),it.lng.toDouble()))
                }
                refreshLocationRecordsMutableLiveData.postValue(System.currentTimeMillis())
            }
            DialogUtils.closeLoadDialog()
        }
    }
    var markerLocation: Marker?=null
    fun runLocationMarker(map: AMap) {
        val markerOption = MarkerOptions()

        markerOption.draggable(false) //设置Marker可拖动
        markerOption.icon(
            AppUtils.getLocationIcon()
        )
        val drivePoint: LatLng = locationRecordsLatLng[0]
        markerLocation?.remove()
        markerLocation =
          map.addMarker(
                markerOption
                    .position(LatLng(drivePoint.latitude, drivePoint.longitude))
//                            .title(it.name)
//                    .snippet("DefaultMarker")
            )
        markerLocation?.isClickable=false
        runIndex=0;
        runLocationMarkerAction(locationRecordsLatLng[0],locationRecordsLatLng[1])
    }
    var runIndex=0;
    var timer :Timer = Timer()
   private fun runLocationMarkerAction(start: LatLng, end: LatLng){
       refreshCompanyPointBeanInfoMutableLiveData.postValue(locationRecords[runIndex])
      var angle=  getAngle(start,end)
        var distance = AMapUtils.calculateLineDistance(start,end)
        val duration = distance*1 // 移动持续时间，单位毫秒
        val startTime = System.currentTimeMillis()
        val interpolator = LinearInterpolator()
        object : TimerTask() {
            override fun run() {
                val elapsed = System.currentTimeMillis() - startTime
                if (elapsed >= duration) {
                    timer.cancel()
                    markerLocation?.position = end
                    runIndex++
                    if(runIndex<locationRecordsLatLng.size-1){
                        runLocationMarkerAction(locationRecordsLatLng[runIndex],locationRecordsLatLng[runIndex+1])
                    }else{
                        refreshCompanyPointBeanInfoMutableLiveData.postValue(locationRecords[locationRecords.size-1])
                    }
                    return
                }
                val t = interpolator.getInterpolation(elapsed.toFloat() / duration)
                val newPos = LatLng(
                    start.latitude + (end.latitude - start.latitude) * t,
                    start.longitude + (end.longitude - start.longitude) * t
                )
                markerLocation?.position = newPos
                markerLocation?.rotateAngle = -angle
            }
        }.let { task ->
            timer  = Timer()
            timer.schedule(task, 0, 16) // 每16毫秒更新一次位置
        }

    }

    private fun getAngle(startPoint: LatLng, endPoint: LatLng): Float {
        if (startPoint == null || endPoint == null) {
            return 0.0f
        }

        val dRotateAngle = atan2(
            abs(startPoint.longitude - endPoint.longitude),
            abs(startPoint.latitude - endPoint.latitude)
        )

        val angle: Double = when {
            endPoint.longitude >= startPoint.longitude -> {
                when {
                    endPoint.latitude >= startPoint.latitude -> dRotateAngle
                    else -> PI - dRotateAngle
                }
            }
            else -> {
                when {
                    endPoint.latitude >= startPoint.latitude -> 2 * PI - dRotateAngle
                    else -> PI + dRotateAngle
                }
            }
        }

        return ((angle * 180f) / PI).toFloat()
    }

}